package com.xiemulei.gulimall.product.service.impl;

import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiemulei.common.constant.ProductConstant;
import com.xiemulei.common.to.SkuHasStockVo;
import com.xiemulei.common.to.SkuReductionTo;
import com.xiemulei.common.to.SpuBoundTo;
import com.xiemulei.common.to.es.SkuEsModel;
import com.xiemulei.common.utils.PageUtils;
import com.xiemulei.common.utils.Query;
import com.xiemulei.common.utils.R;
import com.xiemulei.gulimall.product.dao.SpuInfoDao;
import com.xiemulei.gulimall.product.entity.*;
import com.xiemulei.gulimall.product.feign.CouponFeignService;
import com.xiemulei.gulimall.product.feign.SearchFeignClient;
import com.xiemulei.gulimall.product.feign.WareFeignClient;
import com.xiemulei.gulimall.product.service.*;
import com.xiemulei.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    SpuInfoDescService spuInfoDescService;

    @Resource
    SpuImagesService spuImagesService;

    @Resource
    AttrService attrService;

    @Resource
    ProductAttrValueService productAttrValueService;

    @Resource
    SkuInfoService skuInfoService;

    @Resource
    SkuImagesService skuImagesService;

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Resource
    BrandService brandService;

    @Resource
    CategoryService categoryService;

    @Resource
    WareFeignClient wareFeignClient;

    @Resource
    SearchFeignClient searchFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存 spu 基本信息
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        // 保存 spu 的描述图片
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        // 保存图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(infoEntity.getId(), images);

        // 保存规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity entity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(entity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        // 保存 spu 的 积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存 spu 积分信息失败");
        }

        // 保存当前 spu 对应的 sku 信息
        // sku的基本信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                        String defaultImage = "";
                        for (Images image : item.getImages()) {
                            if (image.getDefaultImg() == 1) {
                                defaultImage = image.getImgUrl();
                            }
                        }
                        SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                        BeanUtils.copyProperties(item, skuInfoEntity);
                        skuInfoEntity.setBrandId(infoEntity.getBrandId());
                        skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                        skuInfoEntity.setSaleCount(0L);
                        skuInfoEntity.setSpuId(infoEntity.getId());
                        skuInfoEntity.setSkuDefaultImg(defaultImage);
                        skuInfoService.saveSkuInfo(skuInfoEntity);

                        Long skuId = skuInfoEntity.getSkuId();

                        List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                                    skuImagesEntity.setSkuId(skuId);
                                    skuImagesEntity.setImgUrl(img.getImgUrl());
                                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                                    return skuImagesEntity;
                                }).filter(entity -> StringUtils.hasLength(entity.getImgUrl()))
                                .collect(Collectors.toList());
                        // sku的图片信息
                        skuImagesService.saveBatch(skuImagesEntities);

                        // sku的销售属性信息
                        List<Attr> attrs = item.getAttr();
                        List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                            SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                            BeanUtils.copyProperties(attr, attrValueEntity);
                            attrValueEntity.setSkuId(skuId);
                            return attrValueEntity;
                        }).collect(Collectors.toList());
                        skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                        // sku的优惠、满减信息
                        SkuReductionTo skuReductionTo = new SkuReductionTo();
                        BeanUtils.copyProperties(item, skuReductionTo);
                        skuReductionTo.setSkuId(skuId);
                        if (skuReductionTo.getFullCount() > 0 ||
                                skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                            R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                            if (r1.getCode() != 0) {
                                log.error("远程保存 sku 优惠信息失败");
                            }
                        }
                    }
            );
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.and((wrapper) -> wrapper.eq("id", key).or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (StringUtils.hasLength(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasLength(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasLength(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 查询当前 sku 所有可以被检索的规格信息（根据spu查询）
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrsIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList =
                baseAttrs
                        .stream()
                        .filter(item -> idSet.contains(item.getAttrId()))
                        .map(item -> {
                            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                            BeanUtils.copyProperties(item, attrs);
                            return attrs;
                        })
                        .collect(Collectors.toList());

        // 发送远程调用，查询是否有库存
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareFeignClient.getSkusHasStock(skuIdList);

            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<>() {
            };

            stockMap = r.getData("data", typeReference)
                    .stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));

        } catch (Exception e) {
            log.error("库存服务查询异常，原因：", e);
        }


        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(skuInfoEntity -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, esModel);
            esModel.setSkuPrice(skuInfoEntity.getPrice());
            esModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            // 设置库存
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            //TODO 热度评分。0
            esModel.setHotScore(0L);
            //查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            // 设置检索属性
            esModel.setAttrs(attrsList);

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            return esModel;
        }).collect(Collectors.toList());

        // 数据发给 es 进行保存
        R r = searchFeignClient.productStatusUp(upProducts);

        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改当前 spu 的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            //TODO 重复调用：接口幂等性
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        if (skuInfo != null) {
            Long spuId = skuInfo.getSpuId();
            return baseMapper.selectById(spuId);
        }
        return null;
    }

}